//
//  ProcessedOrderChild.m
//  rrbi
//
//  Created by mac book on 2019/3/21.
//

#import "ProcessedOrderChild.h"
#import "Pager.h"
#import "MOrder.h"
#import "OrderCell.h"
//#import "OrderHeader.h"
#import "FinishedOrderHeader.h"
#import "FinishedOrderFooter.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "HandleOrderHeader.h"


@interface ProcessedOrderChild ()<HandleOrderHeaderDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) UIView *headerView;

@property(nonatomic,strong) Pager* page;
@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* finishedHeaderIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentitifer;


@property (nonatomic, strong) UIButton *startBtn;
@property (nonatomic, strong) UIButton *endBtn;

@property (nonatomic, strong) NSString *startStr;
@property (nonatomic, strong) NSString *endStr;

@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UILabel *numberLabel;


@end

@implementation ProcessedOrderChild

- (void)viewDidLoad {
    [super viewDidLoad];

    self.cellIdentifier = @"OrderCell";
    self.finishedHeaderIdentifier = @"FinishedOrderHeader";
    self.headerIdentifier = @"HandleOrderHeader";
    self.footerIdentitifer = @"FinishedOrderFooter";
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    
    [self.tableView registerClass:[OrderCell class] forCellReuseIdentifier:self.cellIdentifier];
    [self.tableView registerClass:[HandleOrderHeader class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
    [self.tableView registerClass:[FinishedOrderHeader class] forHeaderFooterViewReuseIdentifier:self.finishedHeaderIdentifier];
    [self.tableView registerClass:[FinishedOrderFooter class] forHeaderFooterViewReuseIdentifier:self.footerIdentitifer];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableHeaderView = [self creatHeaderView];

    [self refreshDataSource];

}

#pragma mark 提交按钮
-(UIView *)creatHeaderView{
    
    self.startStr = self.endStr = @"";

    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
    self.headerView.backgroundColor = [UIColor clearColor];
    
    float button_w = 90;
    float button_h = 30;

    self.startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.startBtn.frame = CGRectMake(15, 15, button_w, button_h);
    [self setUpButton:self.startBtn withText:@"起始时间"];
    
    
    
    self.endBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.endBtn.frame = CGRectMake(CGRectGetMaxX(self.startBtn.frame)+20, CGRectGetMinY(self.startBtn.frame),  button_w, button_h);
    [self setUpButton:self.endBtn withText:@"结束时间"];
    
    
    [self.headerView addSubview:self.priceLabel];
    [self.headerView addSubview:self.numberLabel];

    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.right.equalTo(self.headerView).mas_offset(-15);
        make.bottom.equalTo(self.headerView.mas_centerY);
        
    }];
    
    [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(self.priceLabel);
        make.top.equalTo(self.priceLabel.mas_bottom);
        
    }];
    
    self.priceLabel.text = @"金额：￥0";
    self.numberLabel.text = @"笔数：0";

    
    return self.headerView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
}

#pragma mark =====================================================  Data source
-(void)queryData{
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ince":@"get_order_list",
                          @"sid":[UserModel sharedInstanced].ru_Id,
                          @"page":[WMHelper integerConvertToString:self.page.pageIndex],
                          @"status":self.pass_id,
                          @"starttime":self.startStr,
                          @"endtime":self.endStr,
//                          @"keyword":@"-1"
                          };
    NSLog(@"arg = %@",self.pass_id);
    [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        if(self.page.pageIndex == 1){
            [self.page.arrayData removeAllObjects];
        }
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            self.page.recordCount = [[responseObject objectForKey:@"total"] integerValue];
            self.page.pageSize = [[responseObject objectForKey:@"number"]integerValue];
            NSInteger empty = self.page.recordCount % self.page.pageSize;
            
            self.priceLabel.text = [NSString stringWithFormat:@"金额：￥%@",[responseObject objectForKey:@"total"]];
            self.numberLabel.text = [NSString stringWithFormat:@"笔数：￥%@",[responseObject objectForKey:@"number"]];
            
            if(empty == 0){
                self.page.pageCount = self.page.recordCount/self.page.pageSize;
            }else{
                self.page.pageCount = self.page.recordCount/self.page.pageSize+1;
            }
            
            NSArray* array = [responseObject objectForKey:@"data"];
            if(![WMHelper isNULLOrnil:array]){
                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MOrder* item = [[MOrder alloc]initWithItem:obj];
                    [self.page.arrayData addObject:item];
                }];
            }
        }else{
            [self alertHUD:[responseObject objectForKey:@"msg"]];
        }
        [self.tableView reloadData];
        if(self.page.pageCount<=self.page.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        [weakSelf queryData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf queryData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark =====================================================  <UITableViewDataSource>

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.page.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MOrder* empty =self.page.arrayData[section];
    if(empty.isExpansion){
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    MOrder* empty =self.page.arrayData[indexPath.section];
    cell.arrayGoods =empty.arrayGoods;
    return cell;
}

#pragma mark =====================================================  <UITableViewDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MOrder* empty =self.page.arrayData[indexPath.section];
    if(empty.isExpansion){
        return   empty.arrayGoods.count*60.f;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    MOrder* empty =self.page.arrayData[section];
    if(empty.isExpansion){
        //        return 150.f;
        return 180.f;
    }else{
        //        return   80.f;
        return   100.f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    MOrder* empty =self.page.arrayData[section];
    NSArray *deliveryArr = empty.delivery;
    
    if(empty.isExpansion){
        if (deliveryArr.count == 0) {
            return 250.f;
        }else{
            return 290.f;
        }
    }
    return 0.1;
}
//召唤骑士
-(void)summonKnightWithModel:(MOrder *)empty{
    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"Summon_the_knight",
                          @"sid":[UserModel sharedInstanced].ru_Id,
                          @"order_id":empty.orderID
                          };
    [NetRepositories netSingleConfirm:arg complete:^(EnumNetResponse react, NSDictionary *response, NSString *message) {
        NSString *status = [NSString stringWithFormat:@"%@",response[@"status"]];
        if ([status isEqualToString:@"1"]) {
            
            [self hidHUD:[response objectForKey:@"sucess"]];
            [self refreshDataSource];
        }else{
            [self hidHUD:@"召唤失败"];
        }
        
    }];
}

-(void)inviteWithModel:(MOrder *)empty{
    
    [self showHUD];
    NSDictionary* arg = @{
                          @"ince":@"change_order_status",
                          @"sid":[UserModel sharedInstanced].ru_Id,
                          @"order_sn":empty.orderID
                          };
    NSLog(@"arg = %@",arg);
    [NetRepositories netSingleConfirm:arg complete:^(EnumNetResponse react, NSDictionary *response, NSString *message) {
        NSLog(@"response = %@",response);
        NSInteger flag = [[response objectForKey:@"ret"]integerValue];
        if(flag == 200){
            
            [self hidHUD:[response objectForKey:@"msg"]];
            [self refreshDataSource];
            
        }else{
            
            [self hidHUD:[response objectForKey:@"msg"]];
        }
        
    }];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    MOrder* empty =self.page.arrayData[section];
    if(!empty.isExpansion){
        FinishedOrderHeader* header =  (FinishedOrderHeader*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.finishedHeaderIdentifier];
        [header loadData:empty index:section+1];
        header.delegate = self;
        header.callPersonPhoneBlock = ^{
            NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",empty.phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        };
        
        header.SummonKnightBlock = ^{
            if (empty.status  == OrderStatusAlredayJieDan) {//召唤骑士
                [self summonKnightWithModel:empty];
                
            }else if (empty.status  == OrderStatusWaitInvite){//完成自取
                [self inviteWithModel:empty];
                
            }else{//联系骑手
                MOrder *deliveryModel = empty.delivery.firstObject;
                NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",deliveryModel.emptyPhone];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
                
            }
        };
        return header;
    }else{
        HandleOrderHeader* header =  (HandleOrderHeader*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headerIdentifier];
        [header loadData:empty index:section+1];
        header.delegate = self;
        header.callPersonPhoneBlock = ^{
            NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",empty.phone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        };
        header.SummonKnightBlock = ^{
            NSLog(@"22222");
            if (empty.status  == OrderStatusAlredayJieDan) {//召唤骑士
                [self summonKnightWithModel:empty];
                
            }else if (empty.status  == OrderStatusWaitInvite){//完成自取
                [self inviteWithModel:empty];
                
            }else{//联系骑手
                
                MOrder *deliveryModel = empty.delivery.firstObject;
                NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",deliveryModel.emptyPhone];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
                
            }
        };
        return header;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    MOrder* empty =self.page.arrayData[section];
    if(empty.isExpansion){
        FinishedOrderFooter* footer = (FinishedOrderFooter*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerIdentitifer];
        footer.entity = self.page.arrayData[section];
        footer.callEmptyBlock = ^(MOrder *entity) {
            NSMutableString* str = [[NSMutableString alloc] initWithFormat:@"tel:%@",entity.emptyPhone];
            UIWebView * callWebview = [[UIWebView alloc] init];
            [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
            [self.view addSubview:callWebview];
        };
        
        return footer;
    }
    return [[UIView alloc]init];
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

#pragma mark =====================================================  <OrderHeaderDelegate>
-(void)handleOrderHeader:(MOrder *)entity{
    entity.isExpansion = !entity.isExpansion;
    [self.tableView reloadData];
}

#pragma mark =====================================================  DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无已处理订单" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.tableView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}


#pragma mark =====================================================  property package
-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
    }
    return _page;
}
#pragma mark - 设置Button
-(void)setUpButton:(UIButton *)button withText:(NSString *)str{
    
    [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:button];
    [button setTitle:str forState:UIControlStateNormal];
    button.titleLabel.font =  [UIFont systemFontOfSize:11];
    button.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    [button setTitleColor:[UIColor colorWithWhite:0.3 alpha:1.000] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"downarr"] forState:UIControlStateNormal];
    button.layer.cornerRadius = 30/2;
    button.layer.borderWidth = 0.7;
    button.layer.borderColor = [UIColor lightGrayColor].CGColor;
    
    [self buttonEdgeInsets:button];
    
//    UIView *verticalLine = [[UIView alloc]init];
//    verticalLine.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
//    [button addSubview:verticalLine];
//    verticalLine.frame = CGRectMake(button.frame.size.width - 0.5, 5, 0.5, 30);
}

-(void)buttonEdgeInsets:(UIButton *)button{
    
    [button setTitleEdgeInsets:UIEdgeInsetsMake(0, -button.imageView.bounds.size.width + 2, 0, button.imageView.bounds.size.width + 10)];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, button.titleLabel.bounds.size.width + 10, 0, -button.titleLabel.bounds.size.width + 2)];
    
}

#pragma mark - 按钮点击推出菜单
-(void)clickButton:(UIButton *)button{
    if (button == self.startBtn){
        
        
        [CGXPickerView showDatePickerWithTitle:@"时间" DateType:UIDatePickerModeDate DefaultSelValue:@"" MinDateStr:@"" MaxDateStr:@"" IsAutoSelect:NO Manager:nil ResultBlock:^(NSString *selectValue) {
            
            NSLog(@"%@",selectValue);
            
            [self.startBtn setTitle:selectValue forState:UIControlStateNormal];
            [self buttonEdgeInsets:self.startBtn];
            
            self.startStr = selectValue;
            
            self.page.pageIndex = 1;
            [self queryData];
        }];
        
        
    }else{
        
        [CGXPickerView showDatePickerWithTitle:@"时间" DateType:UIDatePickerModeDate DefaultSelValue:@"" MinDateStr:@"" MaxDateStr:@"" IsAutoSelect:NO Manager:nil ResultBlock:^(NSString *selectValue) {
            
            NSLog(@"%@",selectValue);
            
            [self.endBtn setTitle:selectValue forState:UIControlStateNormal];
            [self buttonEdgeInsets:self.endBtn];
            
            self.endStr = selectValue;
            
            self.page.pageIndex = 1;
            [self queryData];
            
        }];
    }
}

-(UILabel *)priceLabel{
    if (!_priceLabel) {
        _priceLabel = [[UILabel alloc]init];
        _priceLabel.font = [UIFont systemFontOfSize:14.f];
        _priceLabel.textAlignment = NSTextAlignmentRight;
        _priceLabel.textColor = [UIColor colorWithRed:149/255.f green:149/255.f blue:149/255.f alpha:1.0];
    }
    return _priceLabel;
}
-(UILabel *)numberLabel{
    if (!_numberLabel) {
        _numberLabel = [[UILabel alloc]init];
        _numberLabel.font = [UIFont systemFontOfSize:14.f];
        _numberLabel.textAlignment = NSTextAlignmentRight;
        _numberLabel.textColor = [UIColor colorWithRed:149/255.f green:149/255.f blue:149/255.f alpha:1.0];
    }
    return _numberLabel;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
